package util;

import java.io.File;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import javax.naming.InitialContext;

public class MailImplement {
    private Properties props;
    private String mailhost;
    private String user;
    private String password;
    private String protocol;
    private String mailPort;
    private String sslEnabled;
    private String tlsEnabled;

    public MailImplement() {
        InitialContext ic;
        try {
            ic = new InitialContext();
            Session session = (Session)ic.lookup("mail/SSCEmailSession");
            /*
             * Edited by Cuongpt, since 17-Dec-2012
             * get required properties from mail session
             * */
            Properties setupProps = session.getProperties();
            mailhost = setupProps.getProperty("mail.smtp.host");
            mailPort = setupProps.getProperty("mail.smtp.port");
            user = setupProps.getProperty("mail.smtp.user");
            password = setupProps.getProperty("mail.smtp.password");
            sslEnabled = setupProps.getProperty("mail.smtp.ssl.enable");
            tlsEnabled = setupProps.getProperty("mail.smtp.starttls.enable");
            //protocol = props.getProperty("mail.transport.protocol");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public void sendEmail(String to, String subject, String msg, String from,
                          File file) throws MessagingException {
        /*
         * Edited by Cuongpt, since 17-Dec-2012
         * set properties then pass them to mail session
         * */
        if (props == null) {
            props = new Properties();
        }
        props.put("mail.smtp.host", mailhost);
        props.put("mail.smtp.port", mailPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", mailPort);
        //mailProp.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        // SSL check
        if (sslEnabled != null && sslEnabled.equalsIgnoreCase("true")) {
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.socketFactory.class",
                      "javax.net.ssl.SSLSocketFactory");
        }
        if (tlsEnabled != null && tlsEnabled.equalsIgnoreCase("true")) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.socketFactory.class",
                      "javax.net.ssl.SSLSocketFactory");
        }
        // TLS check
        Session session =
            //Session.getInstance(props, new javax.mail.Authenticator() {
            Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, password);
                }
            });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(to));
        message.setSubject(subject, "utf-8");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("Nội dung khiếu nại tố cáo: " + msg, "text/html; charset=UTF-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        if (file != null) {
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(file.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart, "text/html; charset=UTF-8");
        Transport.send(message);
    }

    protected void addAtachments(String[] attachments,
                                 Multipart multipart) throws MessagingException,
                                                             AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            attachmentBodyPart.setFileName(filename);
            multipart.addBodyPart(attachmentBodyPart);
        }
    }
}
